﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.BLL.Cached;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Model;

namespace ZBJF.Warranty.WebProvider
{
    public class WebContext
    {
        private WebContext()
        {
        }

        private static WebContext _instance;
        private static readonly object Lock = new object();
        private static readonly object InsuranceLock = new object();
        public static WebContext Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new WebContext();
                    lock (Lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new WebContext();
                        }
                    }
                }
                return _instance;
            }
        }

        private SystemUser _currentUser;
        public SystemUser CurrentUser
        {
            get
            {
                var userAccount = CookiesHelper.Instance.GetCookie("UserAccount", true);
                var belongApplicationType = CookiesHelper.Instance.GetCookie("BelongApplicationType", true);

                if (_currentUser != null && _currentUser.UserAccount == userAccount &&
                    _currentUser.BelongApplicationType.ToString() == belongApplicationType)
                {
                    return _currentUser;
                }
                else
                {
                    if (!string.IsNullOrEmpty(belongApplicationType) && !string.IsNullOrWhiteSpace(userAccount))
                    {
                        _currentUser =
                            ServiceFactory.SystemUserServiceInstance.Load(
                                (ApplicationType)int.Parse(belongApplicationType), userAccount);
                    }
                    else
                    {
                        _currentUser = null;
                        if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                            HttpContext.Current.Response.Redirect(CommonMethod.GetRedirectUrl(RedirectType.Redirect,
                                    "您还没有登录或登录已经失效，请您先登录（页面即将跳转至登录页面）！", "/Login"));
                    }
                    return _currentUser;
                }
            }
            set
            {
                _currentUser = value;
            }
        }

        public bool CreateInsuranceOrder(InsuranceOrder value, List<InsuranceOrderImage> imageList, ref string orderNo)
        {
            try
            {
                lock (InsuranceLock)
                {
                    var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByIMEIOrIDFV(value.IMEI) ??
                                ServiceFactory.InsuranceOrderServiceInstance.LoadByIMEIOrIDFV(value.IDFV);
                    if (order == null)
                    {
                        //新增
                        var entity = ServiceFactory.InsuranceOrderServiceInstance.AddEntities(new InsuranceOrder
                        {
                            #region Init
                            CardNo = value.CardNo,
                            CardPwd = value.CardPwd,
                            VerificationCertificate = value.VerificationCertificate,
                            OrderNO = CommonMethod.GetNewOrderNo(),//value.OrderNO,
                            InsuranceCategory = value.InsuranceCategory,
                            InsuranceCategoryName = value.InsuranceCategoryName,
                            ProductName = value.ProductName,
                            BuyType = value.BuyType,
                            Price = value.Price,
                            WaitDays = value.WaitDays,
                            EffectiveDate = value.EffectiveDate,
                            PolicyPeriod = value.PolicyPeriod,
                            PolicyPeriodUnit = value.PolicyPeriodUnit,
                            UserName = value.UserName,
                            UserPhone = value.UserPhone,
                            CertificateType = value.CertificateType,
                            CertificateNO = value.CertificateNO,
                            ProductTypeId = value.ProductTypeId,
                            ProductTypeName = value.ProductTypeName,
                            IMEI = value.IMEI,
                            IDFV = value.IDFV,
                            ProductBrandId = value.ProductBrandId,
                            ProductBrandName = value.ProductBrandName,
                            ProductModelId = value.ProductModelId,
                            ProductModelName = value.ProductModelName,
                            SaleVendorId = value.SaleVendorId,
                            SaleVendorName = value.SaleVendorName,
                            SalePersonName = value.SalePersonName,
                            SaleManagerName = value.SaleManagerName,
                            SaleManagerPhone = value.SaleManagerPhone,
                            SaleAddress = value.SaleAddress,
                            OrderStatus = value.OrderStatus,
                            LastCheckUser = value.LastCheckUser,
                            LastCheckTime = value.LastCheckTime,
                            OrderFromType = value.OrderFromType,
                            CreateOrderTime = DateTime.Now,
                            CreateBy = value.CreateBy,
                            LastModifyBy = value.LastModifyBy,
                            LastModifyTime = DateTime.Now
                            #endregion
                        });
                        if (entity.ID <= 0) return false;
                        foreach (var item in imageList)
                        {
                            ServiceFactory.InsuranceOrderImageServiceInstance.AddEntities(new InsuranceOrderImage
                            {
                                InsuranceOrderId = item.InsuranceOrderId,
                                ImageType = item.ImageType,
                                ImageUrl =
                                    CommonMethod.SaveBase64Image(AppConfigCached.GetAppConfig().UploadFileVirtualPath,
                                        item.ImageUrl)
                            });
                        }
                        orderNo = entity.OrderNO;
                        return true;
                    }
                    else
                    {
                        #region Init

                        //order.CardNo = value.CardNo;
                        //order.CardPwd = value.CardPwd;
                        //order.VerificationCertificate = value.VerificationCertificate;
                        //order.OrderNO = value.OrderNO;
                        //order.InsuranceCategory = value.InsuranceCategory;
                        //order.InsuranceCategoryName = value.InsuranceCategoryName;
                        //order.ProductName = value.ProductName;
                        //order.BuyType = value.BuyType;
                        //order.Price = value.Price;
                        //order.WaitDays = value.WaitDays;
                        //order.EffectiveDate = value.EffectiveDate;
                        //order.PolicyPeriod = value.PolicyPeriod;
                        //order.PolicyPeriodUnit = value.PolicyPeriodUnit;
                        if (!string.IsNullOrEmpty(value.UserName))
                            order.UserName = value.UserName;
                        if (!string.IsNullOrEmpty(value.UserPhone))
                            order.UserPhone = value.UserPhone;
                        //if (value.CertificateType)
                        order.CertificateType = value.CertificateType;
                        if (!string.IsNullOrEmpty(value.CertificateNO))
                            order.CertificateNO = value.CertificateNO;
                        if (value.ProductTypeId.HasValue)
                            order.ProductTypeId = value.ProductTypeId;
                        if (!string.IsNullOrEmpty(value.ProductTypeName))
                            order.ProductTypeName = value.ProductTypeName;
                        //order.IMEI = value.IMEI;
                        if (value.ProductBrandId.HasValue)
                            order.ProductBrandId = value.ProductBrandId;
                        if (!string.IsNullOrEmpty(value.ProductBrandName))
                            order.ProductBrandName = value.ProductBrandName;
                        if (value.ProductModelId.HasValue)
                            order.ProductModelId = value.ProductModelId;
                        if (!string.IsNullOrEmpty(value.ProductModelName))
                            order.ProductModelName = value.ProductModelName;
                        //order.SaleVendorId = value.SaleVendorId;
                        //order.SaleVendorName = value.SaleVendorName;
                        //order.SalePersonName = value.SalePersonName;
                        //order.SaleManagerName = value.SaleManagerName;
                        //order.SaleManagerPhone = value.SaleManagerPhone;
                        //order.SaleAddress = value.SaleAddress;
                        //order.OrderStatus = value.OrderStatus;
                        //order.LastCheckUser = value.LastCheckUser;
                        //order.LastCheckTime = value.LastCheckTime;
                        //order.OrderFromType = value.OrderFromType;
                        //order.CreateOrderTime = DateTime.Now;
                        //order.CreateBy = value.CreateBy;
                        if (!string.IsNullOrEmpty(value.LastModifyBy))
                            order.LastModifyBy = value.LastModifyBy;
                        order.LastModifyTime = DateTime.Now;

                        #endregion

                        var flag = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(order);
                        if (!flag) return false;
                        foreach (var item in imageList)
                        {
                            ServiceFactory.InsuranceOrderImageServiceInstance.AddEntities(new InsuranceOrderImage
                            {
                                InsuranceOrderId = item.InsuranceOrderId,
                                ImageType = item.ImageType,
                                ImageUrl = item.ImageUrl
                            });
                        }
                        return flag;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("单例新增/修改订单异常:" + ex.Message + ex.StackTrace);
                return false;
            }
        }

    }
}
